package com.studentmanagement.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.studentmanagement.model.Student;
import com.studentmanagement.service.StudentService;
import com.studentmanagement.util.PageBean;

@WebServlet("/student/*")
public class StudentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private StudentService studentService = new StudentService();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        System.out.println("0.2321");

        if (pathInfo == null || pathInfo.equals("/")) {
            // 列出所有学生
            listStudents(request, response);
        } else if (pathInfo.equals("/add")) {
            System.out.println("111111111111");
            // 显示添加学生表单
            request.getRequestDispatcher("/WEB-INF/student/add.jsp").forward(request, response);
        } else if (pathInfo.equals("/edit")) {
            // 显示编辑学生表单
            showEditForm(request, response);
        } else if (pathInfo.equals("/delete")) {
            // 删除学生
            deleteStudent(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 处理列表页面的分页请求
            listStudents(request, response);
        } else if (pathInfo.equals("/add")) {
            // 添加学生
            addStudent(request, response);
        } else if (pathInfo.equals("/edit")) {
            // 更新学生
            updateStudent(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    private void listStudents(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取分页参数
        System.out.println("5625551");
        int pageNumber = 1;
        int pageSize = 10;
        String sortField = "student_id";
        String sortOrder = "ASC";
        
        try {
            if (request.getParameter("pageNumber") != null) {
                pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            }
            
            if (request.getParameter("pageSize") != null) {
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            }
            
            if (request.getParameter("sortField") != null) {
                sortField = request.getParameter("sortField");
            }
            
            if (request.getParameter("sortOrder") != null) {
                sortOrder = request.getParameter("sortOrder");
            }
        System.out.println("5643513");
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        // 获取分页数据
        PageBean<Student> pageBean = studentService.getStudentsByPage(pageNumber, pageSize, sortField, sortOrder);
        
        // 将数据存入请求属性
        request.setAttribute("pageBean", pageBean);
        
        // 转发到学生列表页面
        request.getRequestDispatcher("/WEB-INF/student/list.jsp").forward(request, response);
    }
    
    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取学生ID
        int studentId = Integer.parseInt(request.getParameter("id"));
        
        // 获取学生信息
        Student student = studentService.getStudentById(studentId);
        
        if (student != null) {
            // 将学生信息存入请求属性
            request.setAttribute("student", student);
            
            // 转发到编辑页面
            request.getRequestDispatcher("/WEB-INF/student/edit.jsp").forward(request, response);
        } else {
            // 学生不存在，重定向到列表页面
            response.sendRedirect(request.getContextPath() + "/student");
        }
    }
    
    private void addStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String birthDateStr = request.getParameter("birthDate");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String enrollmentDateStr = request.getParameter("enrollmentDate");
        String major = request.getParameter("major");
        String status = request.getParameter("status");
        
        try {
            // 解析日期
            Date birthDate = dateFormat.parse(birthDateStr);
            Date enrollmentDate = dateFormat.parse(enrollmentDateStr);
            
            // 创建学生对象
            Student student = new Student();
            student.setName(name);
            student.setGender(gender);
            student.setBirthDate(birthDate);
            student.setAddress(address);
            student.setPhone(phone);
            student.setEmail(email);
            student.setEnrollmentDate(enrollmentDate);
            student.setMajor(major);
            student.setStatus(status);
            
            // 添加学生
            boolean success = studentService.addStudent(student);
            
            if (success) {
                // 添加成功，重定向到列表页面
                response.sendRedirect(request.getContextPath() + "/WEB-INF/student");
            } else {
                // 添加失败，设置错误消息
                request.setAttribute("error", "添加学生失败");
                request.getRequestDispatcher("/WEB-INF/student/add.jsp").forward(request, response);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("error", "日期格式错误");
            request.getRequestDispatcher("/WEB-INF/student/add.jsp").forward(request, response);
        }
    }
    
    private void updateStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        int studentId = Integer.parseInt(request.getParameter("studentId"));
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String birthDateStr = request.getParameter("birthDate");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String enrollmentDateStr = request.getParameter("enrollmentDate");
        String major = request.getParameter("major");
        String status = request.getParameter("status");
        
        try {
            // 解析日期
            Date birthDate = dateFormat.parse(birthDateStr);
            Date enrollmentDate = dateFormat.parse(enrollmentDateStr);
            
            // 创建学生对象
            Student student = new Student();
            student.setStudentId(studentId);
            student.setName(name);
            student.setGender(gender);
            student.setBirthDate(birthDate);
            student.setAddress(address);
            student.setPhone(phone);
            student.setEmail(email);
            student.setEnrollmentDate(enrollmentDate);
            student.setMajor(major);
            student.setStatus(status);
            
            // 更新学生
            boolean success = studentService.updateStudent(student);
            
            if (success) {
                // 更新成功，重定向到列表页面
                response.sendRedirect(request.getContextPath() + "/WEB-INF/student");
            } else {
                // 更新失败，设置错误消息
                request.setAttribute("error", "更新学生失败");
                request.setAttribute("student", student);
                request.getRequestDispatcher("/WEB-INF/student/edit.jsp").forward(request, response);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("error", "日期格式错误");
            request.getRequestDispatcher("/WEB-INF/student/edit.jsp").forward(request, response);
        }
    }
    
    private void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取学生ID
        int studentId = Integer.parseInt(request.getParameter("id"));
        
        // 删除学生
        boolean success = studentService.deleteStudent(studentId);
        
        // 重定向到列表页面
        response.sendRedirect(request.getContextPath() + "/WEB-INF/student");
    }
}

